using System;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using E4RPTools;
using System.Windows.Forms;
using StationCommon;
using DevExpress.Utils;

namespace Station.Controls
{
    public partial class VehicleXtraForm : XtraForm
    {
        private string _plate;
        private VeiculoDataSet _vehicle;
        private Controller _controller;
        
        #region Properties

        public string Plate
        {
            set { _plate = value; }            
        }

        public Controller Controller
        {
            set { _controller = value; }            
        }
        
        #endregion

        #region Private Methods

        private void SetVehicleData()
        {
            _vehicle = new VeiculoDataSet();
            if (_plate == "")
            {
                VeiculoDataSet.VeiculoRow vehicle = _vehicle.Veiculo.NewVeiculoRow();
                vehicle.Matricula = _plate;
                vehicle.IdCliente = "";
                vehicle.NomeCliente = "";
                vehicle.TipoViatura = "";
                vehicle.Modelo = "";
                vehicle.Marca = "";
                vehicle.Cilindrada = "";
                vehicle.CavalosPotencia = "";
                vehicle.TipoCombustivel = "";
                vehicle.NumeroChassis = "";
                vehicle.NumeroMotor = "";
                vehicle.MedidaPneus = "";
                vehicle.PaisOrigem = "";
                vehicle.Observacoes = "";
                vehicle.DataProximaRevisao = DateTime.Now.AddYears(1);
                _vehicle.Veiculo.AddVeiculoRow(vehicle);
            }
            else
                _vehicle.Merge(_controller.GetVehicle(_plate));            
            registrationTextEdit.Enabled = _vehicle.Veiculo[0].Matricula == "";
        }

        private void SetupClientData()
        {
            clienteDataSet.Clear();
            clienteDataSet.Merge(_controller.Clients());
            clientLookUpEdit.Properties.DataSource = clienteDataSet.Cliente;
            clientLookUpEdit.Properties.DisplayMember = clienteDataSet.Cliente.NomeColumn.ToString();
            clientLookUpEdit.Properties.ValueMember = clienteDataSet.Cliente.IdColumn.ToString();
            clientLookUpEdit.Properties.Columns.Clear();
            clientLookUpEdit.Properties.Columns.AddRange(new[] {
                new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupVehicleTypeData()
        {
            tipoVeiculoDataSet.Merge(_controller.VehicleTypes());
            typeLookUpEdit.Properties.DataSource = tipoVeiculoDataSet.TipoVeiculo;
            typeLookUpEdit.Properties.DisplayMember = tipoVeiculoDataSet.TipoVeiculo.NomeColumn.ToString();
            typeLookUpEdit.Properties.ValueMember = tipoVeiculoDataSet.TipoVeiculo.NomeColumn.ToString();
            typeLookUpEdit.Properties.Columns.Clear();
            typeLookUpEdit.Properties.Columns.AddRange(new[] {
                new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupFuelTypeData()
        {
            tipoCombustivelDataSet.Merge(_controller.FuelTypes());
            fuelTypeLookUpEdit.Properties.DataSource = tipoCombustivelDataSet.TipoCombustivel;
            fuelTypeLookUpEdit.Properties.DisplayMember = tipoCombustivelDataSet.TipoCombustivel.NomeColumn.ToString();
            fuelTypeLookUpEdit.Properties.ValueMember = tipoCombustivelDataSet.TipoCombustivel.NomeColumn.ToString();
            fuelTypeLookUpEdit.Properties.Columns.Clear();
            fuelTypeLookUpEdit.Properties.Columns.AddRange(new[] {
                new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupCountryData()
        {
            paisDataSet.Merge(_controller.Countries());
            countryLookUpEdit.Properties.DataSource = paisDataSet.Pais;
            countryLookUpEdit.Properties.DisplayMember = paisDataSet.Pais.NomeColumn.ToString();
            countryLookUpEdit.Properties.ValueMember = paisDataSet.Pais.NomeColumn.ToString();
            countryLookUpEdit.Properties.Columns.Clear();
            countryLookUpEdit.Properties.Columns.AddRange(new[] {
                new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void GetDataFromControls()
        {
            _vehicle.Veiculo[0].Matricula = registrationTextEdit.Text;
            _vehicle.Veiculo[0].NomeCliente = clientLookUpEdit.Text;
            if (clientLookUpEdit.EditValue == null)
                _vehicle.Veiculo[0].SetIdClienteNull();
            else
                _vehicle.Veiculo[0].IdCliente = (string)clientLookUpEdit.EditValue;
            _vehicle.Veiculo[0].TipoViatura = typeLookUpEdit.Text;
            _vehicle.Veiculo[0].Modelo = modelTextEdit.Text;
            _vehicle.Veiculo[0].Marca = makeTextEdit.Text;
            _vehicle.Veiculo[0].Cilindrada = engineCapacityTextEdit.Text;
            _vehicle.Veiculo[0].CavalosPotencia = powerTextEdit.Text;            
            _vehicle.Veiculo[0].TipoCombustivel = fuelTypeLookUpEdit.Text;            
            _vehicle.Veiculo[0].NumeroChassis = chassisTextEdit.Text;
            _vehicle.Veiculo[0].NumeroMotor = engineNumberTextEdit.Text;
            _vehicle.Veiculo[0].MedidaPneus = wheelTextEdit.Text;
            if (productionDateEdit.EditValue == null)
                _vehicle.Veiculo[0].SetDataFabricoNull();
            else
                _vehicle.Veiculo[0].DataFabrico = (DateTime)productionDateEdit.EditValue;
            if (registrationDateEdit.EditValue == null)
                _vehicle.Veiculo[0].SetDataMatriculaNull();
            else
                _vehicle.Veiculo[0].DataMatricula = (DateTime)registrationDateEdit.EditValue;
            if (kmsCalcEdit.EditValue == null)
                _vehicle.Veiculo[0].SetKmsNull();
            else
                _vehicle.Veiculo[0].Kms = Convert.ToInt64(kmsCalcEdit.EditValue);
            if (nextKmsCalcEdit.EditValue == null)
                _vehicle.Veiculo[0].SetKmsProximaRevisaoNull();
            else
                _vehicle.Veiculo[0].KmsProximaRevisao = Convert.ToInt64(nextKmsCalcEdit.EditValue);
            if (nextRevisionDateEdit.EditValue == null)
                _vehicle.Veiculo[0].SetDataProximaRevisaoNull();
            else
                _vehicle.Veiculo[0].DataProximaRevisao = (DateTime)nextRevisionDateEdit.EditValue;
            if (inspectionDateEdit.EditValue == null)
                _vehicle.Veiculo[0].SetDataInspeccaoNull();
            else
                _vehicle.Veiculo[0].DataInspeccao = (DateTime)inspectionDateEdit.EditValue;
            if (nextInspectionDateEdit.EditValue == null)
                _vehicle.Veiculo[0].SetDataProximaInspeccaoNull();
            else
                _vehicle.Veiculo[0].DataProximaInspeccao = (DateTime)nextInspectionDateEdit.EditValue;
            _vehicle.Veiculo[0].PaisOrigem = countryLookUpEdit.Text;
            if (frontWeightCalcEdit.EditValue == null)
                _vehicle.Veiculo[0].SetPesoEixoFrenteNull();
            else
                _vehicle.Veiculo[0].PesoEixoFrente = Convert.ToInt64(frontWeightCalcEdit.EditValue);
            if (rearWeightCalcEdit.EditValue == null)
                _vehicle.Veiculo[0].SetPesoEixoTrasNull();
            else
                _vehicle.Veiculo[0].PesoEixoTras = Convert.ToInt64(rearWeightCalcEdit.EditValue);
            _vehicle.Veiculo[0].Observacoes = remarksMemoEdit.Text;
        }

        private void SetDataToControls()
        {
            registrationTextEdit.Text = _vehicle.Veiculo[0].Matricula;
            clientLookUpEdit.EditValue = _vehicle.Veiculo[0].IsIdClienteNull() ? "" : _vehicle.Veiculo[0].IdCliente;
            typeLookUpEdit.Text = _vehicle.Veiculo[0].TipoViatura;
            modelTextEdit.Text = _vehicle.Veiculo[0].Modelo;
            makeTextEdit.Text = _vehicle.Veiculo[0].Marca;
            engineCapacityTextEdit.Text = _vehicle.Veiculo[0].Cilindrada;
            powerTextEdit.Text = _vehicle.Veiculo[0].CavalosPotencia;
            fuelTypeLookUpEdit.Text = _vehicle.Veiculo[0].TipoCombustivel;
            chassisTextEdit.Text = _vehicle.Veiculo[0].NumeroChassis;
            engineNumberTextEdit.Text = _vehicle.Veiculo[0].NumeroMotor;
            wheelTextEdit.Text = _vehicle.Veiculo[0].MedidaPneus;
            productionDateEdit.EditValue = _vehicle.Veiculo[0].IsDataFabricoNull() ? null : (object)_vehicle.Veiculo[0].DataFabrico;
            registrationDateEdit.EditValue = _vehicle.Veiculo[0].IsDataMatriculaNull() ? null : (object)_vehicle.Veiculo[0].DataMatricula;
            kmsCalcEdit.EditValue = _vehicle.Veiculo[0].IsKmsNull() ? null : (object)_vehicle.Veiculo[0].Kms;
            nextKmsCalcEdit.EditValue = _vehicle.Veiculo[0].IsKmsProximaRevisaoNull() ? null : (object)_vehicle.Veiculo[0].KmsProximaRevisao;
            nextRevisionDateEdit.EditValue = _vehicle.Veiculo[0].DataProximaRevisao;
            inspectionDateEdit.EditValue = _vehicle.Veiculo[0].IsDataInspeccaoNull() ? null : (object)_vehicle.Veiculo[0].DataInspeccao;
            nextInspectionDateEdit.EditValue = _vehicle.Veiculo[0].IsDataProximaInspeccaoNull() ? null : (object)_vehicle.Veiculo[0].DataProximaInspeccao;
            countryLookUpEdit.Text = _vehicle.Veiculo[0].PaisOrigem;
            frontWeightCalcEdit.EditValue = _vehicle.Veiculo[0].IsPesoEixoFrenteNull() ? null : (object)_vehicle.Veiculo[0].PesoEixoFrente;
            rearWeightCalcEdit.EditValue = _vehicle.Veiculo[0].IsPesoEixoTrasNull() ? null : (object)_vehicle.Veiculo[0].PesoEixoTras;
            remarksMemoEdit.Text = _vehicle.Veiculo[0].Observacoes;
        }

        private void ClearControlErrors()
        {
            dxErrorProvider.SetError(registrationTextEdit, "");
            dxErrorProvider.SetError(clientLookUpEdit, "");
            dxErrorProvider.SetError(typeLookUpEdit, "");
            dxErrorProvider.SetError(modelTextEdit, "");
            dxErrorProvider.SetError(makeTextEdit, "");
            dxErrorProvider.SetError(engineCapacityTextEdit, "");
            dxErrorProvider.SetError(powerTextEdit, "");
            dxErrorProvider.SetError(fuelTypeLookUpEdit, "");
            dxErrorProvider.SetError(chassisTextEdit, "");
            dxErrorProvider.SetError(engineNumberTextEdit, "");
            dxErrorProvider.SetError(wheelTextEdit, "");
            dxErrorProvider.SetError(productionDateEdit, "");
            dxErrorProvider.SetError(registrationDateEdit, "");
            dxErrorProvider.SetError(kmsCalcEdit, "");
            dxErrorProvider.SetError(nextKmsCalcEdit, "");
            dxErrorProvider.SetError(nextRevisionDateEdit, "");
            dxErrorProvider.SetError(nextInspectionDateEdit, "");
            dxErrorProvider.SetError(inspectionDateEdit, "");
            dxErrorProvider.SetError(countryLookUpEdit, "");
            dxErrorProvider.SetError(rearWeightCalcEdit, "");
            dxErrorProvider.SetError(frontWeightCalcEdit, "");
            dxErrorProvider.SetError(remarksMemoEdit, "");
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "Matricula":
                    return registrationTextEdit;
                case "ClienteNome":
                case "ClienteIdExterno":
                    return clientLookUpEdit;
                case "Marca":
                    return makeTextEdit;
                case "Modelo":
                    return modelTextEdit;
                case "TipoViatura":
                    return typeLookUpEdit;
                case "CavalosPotencia":
                    return powerTextEdit;
                case "Cilindrada":
                    return engineCapacityTextEdit;
                case "Combustivel":
                    return fuelTypeLookUpEdit;
                case "NumeroChassis":
                    return chassisTextEdit;
                case "MedidaPneus":
                    return wheelTextEdit;
                case "DataFabrico":
                    return productionDateEdit;
                case "DataMatricula":
                    return registrationDateEdit;
                case "Kms":
                    return kmsCalcEdit;
                default:
                    return null;
            }
        }

        private void SetControlErrors(Result result)
        {
            foreach (Error error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        #endregion Private Methods

        public VehicleXtraForm()
        {
            InitializeComponent();
            Load += VehicleXtraForm_Load;
            okSimpleButton.Click += okSimpleButton_Click;
        }
        
        void VehicleXtraForm_Load(object sender, EventArgs e)
        {
            SetVehicleData();
            SetupClientData();
            SetupVehicleTypeData();
            SetupFuelTypeData();
            SetupCountryData();
            SetDataToControls();
        }

        void okSimpleButton_Click(object sender, EventArgs e)
        {
            ClearControlErrors();
            GetDataFromControls();
            Result result = _controller.IsVehicleValid(_vehicle.Veiculo[0]);
            if (result.Failed)
            {
                DialogResult = DialogResult.None;
                SetControlErrors(result);
            }
            else
                _controller.SaveVehicle(_vehicle.Veiculo[0]);
        }

    }
}